<template>
  <div class="app-container">
    <div id="map">
      <Map
        :deviceCategoryList="deviceCategoryList"
        :lineData="
          tableLineData.filter((item) =>
            searchLayerValue.length > 0 && activeTab == 'first'
              ? item.inspLineName.indexOf(String(searchLayerValue)) > -1
              : true
          )
        "
        :dangerData="
          tableDangerData.filter((item) =>
            searchLayerValue.length > 0 && activeTab == 'second'
              ? item.dangerName.indexOf(String(searchLayerValue)) > -1
              : true
          )
        "
        :mapCenter="mapCenter"
        :inspUserPosition="currentInspUserPositionData"
        :inspUserPositionOne="
          showDangerList
            ? inspData.status == 2
              ? [currentInspUserPositionData[0]]
              : currentInspUserPositionData
            : currentInspUserPositionData
        "
        :inspLineId="currentInspLineId"
      />
      <Widgets :deviceCategoryList="deviceCategoryList" />
    </div>
    <!-- <tool :gmap="gmap" /> -->
    <el-row class="tool">
      <!-- <el-col :span="6">
        <el-select
          placeholder="请选择"
          v-model="searchType"
          style="width: 80px; margin-right: 5px"
          size="small"
        >
          <el-option label="设备" :value="1 * 1" />
          <el-option label="地图" :value="2 * 1" />
        </el-select>
        <el-input
          v-model="searchValue"
          :placeholder="
            searchType == 1
              ? '请输入管点/段编号、名称、区域'
              : '请输入需要搜索的地址'
          "
          style="width: 280px"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </el-col> -->
      <div>
        <el-button @click="f_ShowLayer" type="primary" size="small">
          图 层
        </el-button>
        <el-button @click="f_ShowDangerList" type="primary">
          <p>人 员</p>
          <p>轨 迹</p>
        </el-button>
        <el-button @click="f_CloseDialog" type="primary">
          <p>返 回</p>
          <p>列 表</p>
        </el-button>
      </div>
    </el-row>
    <div v-if="showDangerList" class="content-danger-region">
      <div class="title">人员轨迹</div>
      <div class="content pb-[0px!Imortant] mb-[12px]">
        <el-row
          v-for="(item, index) in inspUserData"
          :class="{ active: activeInspUserIndex == index }"
          class="p-[8px]"
          @click="f_ChangeInspUser(index)"
        >
          <el-col :span="4">
            <img
              src="../../../../assets/images/person.png"
              class="w-[30px] mt-[16px] ml-[16px]"
            />
          </el-col>
          <el-col :span="20">
            <el-row>
              <el-col :span="12">{{ item.inspUserName }}</el-col>
              <el-col
                :span="12"
                v-if="item.status == 1"
                class="text-right color-green"
                >【在线】</el-col
              >
              <el-col
                :span="12"
                v-if="item.status == 2"
                class="text-right color-green"
                >【已完成】</el-col
              >
              <el-col
                :span="12"
                v-if="item.status == 3"
                class="text-right color-red"
                >【暂停】</el-col
              >
              <el-col
                :span="12"
                v-if="item.status == 4"
                class="text-right color-green"
                >【系统自动完成】</el-col
              >
            </el-row>
            <el-row>
              <el-col :span="12">{{ item.planSetName }}</el-col>
              <el-col :span="12" class="text-right">{{ item.taskName }}</el-col>
            </el-row>
            <el-row
              >当前位置： <span>{{ item.address }}</span></el-row
            >
          </el-col>
        </el-row>
      </div>
      <div class="content pt-[10px] pr-[10px]">
        <el-button-group class="w-[100%] mb-[12px]">
          <el-button
            :type="btnType == 'xj' ? 'primary' : ''"
            class="w-[50%]"
            @click="btnType = 'xj'"
            >巡检信息</el-button
          >
          <el-button
            :type="btnType == 'yh' ? 'primary' : ''"
            class="w-[50%]"
            @click="btnType = 'yh'"
          >
            隐患信息
          </el-button>
        </el-button-group>
        <el-table
          v-if="btnType == 'xj'"
          :data="tableData"
          border
          header-row-class-name="table-header"
          ref="tableRef"
          size="small"
          :height="tableHeight"
          highlight-current-row
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column
            label="管点名称"
            prop="inspDestName"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.point.pointName }} {{ scope.row.point.pointGisNo }}
            </template>
          </el-table-column>
          <el-table-column
            label="地址"
            prop="dangerCount"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.point.address }}
            </template>
          </el-table-column>
          <el-table-column
            label="是否完成检查"
            prop="warnCount"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.isWrite ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column
            label="是否发现隐患"
            prop="historyCount"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span v-if="f_IsDanger(scope.row)" style="color: red">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="btnType == 'yh'" class="danger">
          <div v-for="item in taskDangerData">
            <p>
              <span>隐患名称：</span>{{ item.dangerName }}
              <el-button
                type="primary"
                class="float-right"
                @click="f_OpenDialog(item)"
                >查看详情</el-button
              >
            </p>
            <p><span>隐患描述：</span>{{ item.dangerContent }}</p>
            <p>
              <span>隐患等级:</span>
              <el-tag v-if="item.level == 3" type="success">低</el-tag>
              <el-tag v-if="item.level == 2" type="warning">中</el-tag>
              <el-tag v-if="item.level == 1" type="danger">高</el-tag>
            </p>
            <p><span>地址：</span>{{ item.address }}</p>
            <p><span>上报时间：</span>{{ item.reportTime }}</p>
          </div>
        </div>
      </div>
    </div>
    <div v-if="showLayer" class="content-danger-region">
      <div>
        <div class="title">图层列表</div>
        <div class="search">
          <el-form
            ref="formRef"
            :inline="true"
            size="small"
            label-width="100"
            label-position="left"
          >
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item prop="polygonId">
                  <el-input
                    v-model="searchLayerValue"
                    :placeholder="
                      activeTab == 'first'
                        ? '请输入巡检线路名称搜索'
                        : activeTab == 'second'
                          ? '请输入隐患名称搜索'
                          : '请输入人员姓名搜索'
                    "
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="table">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="巡检线路" name="first">
              <el-table
                :data="
                  tableLineData.filter((item) =>
                    searchLayerValue.length > 0 && activeTab == 'first'
                      ? item.inspLineName.indexOf(String(searchLayerValue)) > -1
                      : true
                  )
                "
                border
                header-row-class-name="table-header"
                ref="tableLineRef"
                size="small"
                :height="tableHeightLayer"
                highlight-current-row
                @selection-change="f_HandleSelectionChange('line')"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />
                <el-table-column
                  label="线路名称"
                  prop="inspLineName"
                  align="center"
                />
                <el-table-column
                  label="是否显示"
                  prop="dangerName"
                  align="center"
                >
                  <template #header>
                    全选
                    <el-checkbox
                      class="align-bottom"
                      @change="f_ChangeDangerData('line')"
                      v-model="lineCheckedValue"
                    ></el-checkbox>
                  </template>
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.checked"
                      @change="f_ChangeDangerData"
                    ></el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="隐患名称" name="second">
              <el-table
                :data="
                  tableDangerData1.filter((item) =>
                    searchLayerValue.length > 0 && activeTab == 'second'
                      ? item.dangerName.indexOf(String(searchLayerValue)) > -1
                      : true
                  )
                "
                border
                header-row-class-name="table-header"
                ref="tableDangerRef1"
                size="small"
                highlight-current-row
                :height="tableHeightLayer / 2 - 10"
                @selection-change="f_HandleSelectionChange('danger')"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />
                <!-- <el-table-column type="selection" width="50" align="center" /> -->
                <el-table-column
                  label="隐患名称"
                  prop="dangerName"
                  align="center"
                />
                <el-table-column
                  label="是否显示"
                  prop="dangerName"
                  align="center"
                >
                  <template #header>
                    全选
                    <el-checkbox
                      class="align-bottom"
                      @change="f_ChangeDangerData('danger1')"
                      v-model="danger1CheckedValue"
                    ></el-checkbox>
                  </template>
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.checked"
                      @change="f_ChangeDangerData"
                    ></el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
              <el-table
                class="mt-[15px]"
                :data="
                  tableDangerData2.filter((item) =>
                    searchLayerValue.length > 0 && activeTab == 'second'
                      ? item.dangerName.indexOf(String(searchLayerValue)) > -1
                      : true
                  )
                "
                border
                header-row-class-name="table-header"
                ref="tableDangerRef2"
                size="small"
                highlight-current-row
                :height="tableHeightLayer / 2 - 10"
                @selection-change="f_HandleSelectionChange('danger')"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />
                <!-- <el-table-column type="selection" width="50" align="center" /> -->
                <el-table-column
                  label="预警名称"
                  prop="dangerName"
                  align="center"
                />
                <el-table-column
                  label="是否显示"
                  prop="dangerName"
                  align="center"
                >
                  <template #header>
                    全选
                    <el-checkbox
                      class="align-bottom"
                      @change="f_ChangeDangerData('danger2')"
                      v-model="danger2CheckedValue"
                    ></el-checkbox>
                  </template>
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.checked"
                      size="large"
                      @change="f_ChangeDangerData"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="人员轨迹" name="third">
              <el-table
                :data="
                  tablePersonData.filter((item) =>
                    searchLayerValue.length > 0 && activeTab == 'third'
                      ? item.inspLineName.indexOf(String(searchLayerValue)) > -1
                      : true
                  )
                "
                border
                header-row-class-name="table-header"
                ref="tablePersonRef"
                size="small"
                :height="tableHeightLayer"
                highlight-current-row
                @selection-change="f_HandleSelectionChange('person')"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />

                <el-table-column
                  label="在线人员姓名"
                  prop="inspUserName"
                  align="center"
                />
                <el-table-column
                  label="是否显示"
                  prop="dangerName"
                  align="center"
                >
                  <template #header>
                    全选
                    <el-checkbox
                      class="align-bottom"
                      @change="f_ChangeDangerData('person')"
                      v-model="personCheckedValue"
                    ></el-checkbox>
                  </template>
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.checked"
                      @change="f_ChangeDangerData"
                    ></el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      title="隐患详情"
      size="1400"
      append-to-body
      @close="f_CloseDialog"
      class="bg-[#f5f5f5!important]"
      destroy-on-close
    >
      <edit_drawer :form="formData" @close="f_CloseDialog" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Inspection",
  inheritAttrs: false,
});
import { getAddressByLonLat } from "@/utils/map";
import ClusterSwitch from "./components/Widgets/ClusterSwitch/index.vue";
import Map from "./components/Map/index.vue";
import Widgets from "./components/Widgets/index.vue";
import TaskSetAPI from "@/api/TaskSetAPI";
import { useDeviceCategory } from "@/views/pipe-network/hooks/useDeviceCategory";
import { find } from "lodash";
import tool from "./tool/index.vue";
import { Search } from "@element-plus/icons-vue";
import DangerAPI from "@/api/DangerAPI";
import moment from "moment";
import LineAPI from "@/api/LineAPI";
import GisPointInfoAPI from "@/api/GisPointInfoAPI";
import DeviceCategoryApi from "@/api/DeviceCategoryApi";
import edit_drawer from "./../../danger/detail.vue";
import { queryAreaInfoList } from "@/api/pipe";
import TaskAPI from "@/api/TaskAPI";
const emits = defineEmits(["close"]);
const deviceCategoryList = ref("");
const dialogVisible = ref(true);
const mapCenter = ref([]);
const activeInspUserIndex = ref(0);
const dialog = reactive({
  visible: false,
});
const props = defineProps(["form"]);
const inspData = ref(props.form);
let searchType = ref(1);
let searchValue = ref("");
let searchLayerValue = ref("");
let searchLineValue = ref("");

const toggleShowLayerManager = () => {
  isShowLayerManager.value = !isShowLayerManager.value;
};

// 返回地址
function f_GetAddress(data, index) {
  getAddressByLonLat(data.longitude, data.latitude).then((res) => {
    if (res.status === "1") {
      const str = res.regeocode.formatted_address;
      inspUserData.value[index].address = str;
    }
  });
}

// 返回地址
function f_GetAddressOver(longitude, latitude) {
  getAddressByLonLat(longitude, latitude).then((res) => {
    if (res.status === "1") {
      const str = res.regeocode.formatted_address;
      inspUserData.value[0].address = str;
    }
  });
}

// 关闭弹框
function f_CloseDialog() {
  emits("close");
}
// 弹框 隐患详情
function f_OpenDialog(data) {
  // let dangerData = find(tableDangerData.value, { dangerId: data.dangerId });
  formData.value = data;
  dialog.visible = true;
}

// 返回图片
function f_GetPath(data: any) {
  let index = 1;
  if (data.classId) {
    let typeData = find(tablePointTypeData.value, { classId: data.classId });
    if (typeData) {
      index = typeData.image;
    }
  }
  return Number(index);
}

let tableHeight = ref(0);
let tableHeightLayer = ref(0);
let activeTag = ref(1);
const tableData = ref([]);
const tableDataDetail = ref([]);
const tableDataDetail1 = ref([]);
const tableDataDetail2 = ref([]);

const tableLineData = ref([]);
const tablePointData = ref([]);
const tablePointTypeData = ref([]);
const tableDangerData = ref([]);
const tableDangerData1 = ref([]);
const tableDangerData2 = ref([]);
const tablePersonData = ref([]);

const tableLineRef = ref();
const tableDangerRef = ref();
const tableDangerRef1 = ref();
const tableDangerRef2 = ref();
const tablePersonRef = ref();

const checkedLineData = ref([]);
const checkedDangerData = ref([]);
const checkedPersonData = ref([]);

const showDangerList = ref(false);
const showDangerDetail = ref(false);
const showLayer = ref(false);
const dangerDetailData = ref([]);
const activeDanger = ref({});
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 1000,
});
const selectData = ref([]);
const activeTab = ref("first");
const lineData = ref([]);

const showTable = ref(true);

const tableDetailHeight = ref(334);

const btnType = ref("xj");
const inspUserData = ref([]);
const taskDangerData = ref([]);
const currentInspUserPositionData = ref([]);

const lineCheckedValue = ref(true);
const danger1CheckedValue = ref(true);
const danger2CheckedValue = ref(true);
const personCheckedValue = ref(true);
const currentInspLineId = ref("");

const zoom = ref(12);
let gmap = null;

const formData = ref({});

function onMapReady(instance: any) {
  gmap = instance;
  console.log(instance);
}

function f_ChangeMap() {
  gmap.zoomIn();
}

window.addEventListener("keydown", function (e) {
  if (e.keyCode == 27) {
    e.preventDefault();
  }
});

const detaitWidth = ref(document.body.clientWidth - 880);
let isFullscreen = ref(false);
const onFullScreen = () => {
  // if (screenfull.isEnabled) {
  //   const el = document.querySelector(".content-danger-detail");
  //   el && screenfull.toggle(el);
  //   isFullscreen.value = !screenfull.isFullscreen;
  // }
  // showTable.value = !showTable.value;
  // setTimeout(() => {
  //   showTable.value = !showTable.value;
  //   console.log(isFullscreen.value);
  //   if (isFullscreen.value) {
  //     tableDetailHeight.value = window.innerHeight - 66;
  //   } else {
  //     tableDetailHeight.value = 334;
  //   }
  // }, 100);
  showTable.value = !showTable.value;
  setTimeout(() => {
    showTable.value = !showTable.value;
    if (tableDetailHeight.value > 400) {
      tableDetailHeight.value = 334;
      detaitWidth.value = document.body.clientWidth - 850;
    } else {
      tableDetailHeight.value = window.innerHeight - 194;
      detaitWidth.value = document.body.clientWidth - 280;
    }
  }, 100);
};

// 切换巡检人员
function f_ChangeInspUser(userIndex) {
  activeInspUserIndex.value = userIndex;
  f_HandelQueryDetail(inspUserData.value[userIndex].taskId);
  f_HandelQueryAreaByLineId(inspUserData.value[userIndex].inspDestId);

  // 重置相应数据
  tableLineData.value.forEach((item, index) => {
    if (item.inspLineId != inspUserData.value[userIndex].inspDestId) {
      tableLineData.value[index].checked = false;
    } else {
      tableLineData.value[index].checked = true;
    }
  });
  currentInspUserPositionData.value.forEach((item, index) => {
    if (item.inspUserId != inspUserData.value[userIndex].inspUserId) {
      currentInspUserPositionData.value[index].checked = false;
    } else {
      currentInspUserPositionData.value[index].checked = true;
    }
  });
  currentInspUserPositionData.value = JSON.parse(
    JSON.stringify(currentInspUserPositionData.value)
  );
  tableLineData.value = JSON.parse(JSON.stringify(tableLineData.value));
  mapCenter.value = [
    inspUserData.value[userIndex].latitude,
    inspUserData.value[userIndex].longitude,
  ];
}

// change 隐患的勾选
function f_ChangeDangerData(flag) {
  if (flag == "line") {
    tableLineData.value.forEach((item, index) => {
      tableLineData.value[index].checked = lineCheckedValue.value;
    });
  }
  if (flag == "danger1") {
    tableDangerData1.value.forEach((item, index) => {
      tableDangerData1.value[index].checked = danger1CheckedValue.value;
    });
  }
  if (flag == "danger2") {
    tableDangerData2.value.forEach((item, index) => {
      tableDangerData2.value[index].checked = danger2CheckedValue.value;
    });
  }
  if (flag == "person") {
    tablePersonData.value.forEach((item, index) => {
      tablePersonData.value[index].checked = personCheckedValue.value;
    });
    currentInspUserPositionData.value.forEach((item, index) => {
      currentInspUserPositionData.value[index].checked =
        personCheckedValue.value;
    });
  }
  currentInspUserPositionData.value.forEach((item, index) => {
    let isChecked = find(tablePersonData.value, {
      inspUserId: item.inspUserId,
    }).checked;
    currentInspUserPositionData.value[index].checked = isChecked;
  });

  tableDangerData1.value = JSON.parse(JSON.stringify(tableDangerData1.value));
  tableDangerData2.value = JSON.parse(JSON.stringify(tableDangerData2.value));
  tableDangerData.value = tableDangerData1.value.concat(tableDangerData2.value);
  tablePersonData.value = JSON.parse(JSON.stringify(tablePersonData.value));
  currentInspUserPositionData.value = JSON.parse(
    JSON.stringify(currentInspUserPositionData.value)
  );

  console.log(currentInspUserPositionData.value);

  // 判断是否全选
  danger1CheckedValue.value = find(tableDangerData1.value, { checked: false })
    ? false
    : true;
  danger2CheckedValue.value = find(tableDangerData2.value, { checked: false })
    ? false
    : true;
  personCheckedValue.value = find(tablePersonData.value, { checked: false })
    ? false
    : true;
  lineCheckedValue.value = find(tableLineData.value, { checked: false })
    ? false
    : true;
}

// 选中表格行
function f_CheckedTableRow(type: String) {
  // if (type == "line") {
  //   setTimeout(() => {
  //     tableLineRef.value.toggleAllSelection();
  //     tableDangerRef1.value.toggleAllSelection();
  //     tableDangerRef2.value.toggleAllSelection();
  //     tablePersonRef.value.toggleAllSelection();
  //   }, 200);
  // }
}

// 表格 选中 改变
function f_HandleSelectionChange(type) {
  if (type == "line") {
    let tempData = tableLineRef.value.getSelectionRows();
    checkedLineData.value = tempData;
  } else if (type == "danger") {
    // let tempData1 = tableDangerRef1.value.getSelectionRows();
    // let tempData2 = tableDangerRef2.value.getSelectionRows();
    // checkedDangerData.value = tempData1.concat(tempData1);
    // checkedDangerData.value.forEach(item => {
    //   tableDangerData
    // })
  } else {
    let tempData = tablePersonRef.value.getSelectionRows();
    checkedPersonData.value = tempData;
  }
}

// 查询
function f_HandelQuery() {
  DangerAPI.api_query_count(queryParams).then(({ data, succeeded }) => {
    if (succeeded) {
      tableData.value = data;
    }
  });
}

import { groupBy, forIn } from "lodash";
// 查询 今日巡检人员
function f_HandelQueryPosition() {
  // let params = {
  //   StartTime: moment(new Date()).format("YYYY-MM-DD 00:00:00"),
  //   EndTime: moment(new Date()).format("YYYY-MM-DD 23:59:59"),
  // };
  let params = {
    StartTime: "",
    EndTime: "",
  };
  if (inspData.value.status == 1 || inspData.value.status == 3) {
    params.StartTime = moment(new Date()).format("YYYY-MM-DD 00:00:00");
    params.EndTime = moment(new Date()).format("YYYY-MM-DD 23:59:59");

    DangerAPI.api_insp_task_user(params).then(({ data, succeeded }) => {
      if (succeeded) {
        inspUserData.value = data;
        inspUserData.value.forEach((item, index) => {
          f_GetAddress(item, index);
        });
        tablePersonData.value = data;
        tablePersonData.value.forEach((item, index) => {
          tablePersonData.value[index].checked = true;
        });
        checkedPersonData.value = data;
        f_HandelQueryUserPosition(null, params.StartTime, params.EndTime);
        f_HandelQueryDetail(inspUserData.value[0].taskId);
      }
    });
  } else {
    // params.StartTime = inspData.value.beginTime;
    // params.EndTime = inspData.value.doneTime;

    // DangerAPI.api_insp_task_user(params).then(({ data, succeeded }) => {
    //   if (succeeded) {
    inspUserData.value = [inspData.value];
    // inspUserData.value.forEach((item, index) => {
    //   f_GetAddress(item, index);
    // });
    tablePersonData.value = [inspData.value];
    tablePersonData.value.forEach((item, index) => {
      tablePersonData.value[index].checked = true;
    });
    // checkedPersonData.value = [inspData.value];
    // f_HandelQueryUserPosition(
    //   inspData.value.inspUserId,
    //   params.StartTime,
    //   params.EndTime
    // );
    let params = {
      StartTime: inspData.value.beginTime,
      EndTime: inspData.value.doneTime,
      TaskId: inspData.value.taskId,
    };
    DangerAPI.api_query_positon_by_task(params).then(({ data, succeeded }) => {
      if (succeeded) {
        let groupedBatchId = groupBy(data, "batchId");

        forIn(groupedBatchId, (value, key) => {
          currentInspUserPositionData.value.push({
            inspUserId: inspData.value.inspUserId,
            inspUserName: inspData.value.inspUserName,
            positions: value,
          });
        });
        if (data && data.length) {
          f_GetAddressOver(data[0].longitude, data[0].latitude);
        }

        currentInspUserPositionData.value = JSON.parse(
          JSON.stringify(currentInspUserPositionData.value)
        );
      }
    });

    f_HandelQueryDetail(inspUserData.value[0].taskId);
    //   }
    // });
  }
}

// 查询 管点
function f_HandleQueryPointLine() {
  let params = {
    pageSize: 100000,
    pageIndex: 1,
    isCoordinate: true,
  };
  GisPointInfoAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      tablePointData.value = data.items
        .filter((item: any) => item.jsonGeom)
        .map((item: any) => {
          const [lng, lat] = JSON.parse(item.jsonGeom).coordinates;
          return {
            ...item,
            latlng: [lat, lng],
          };
        });
    }
  });
}

// 查询 管点
function f_HandleQueryPointLineType() {
  let params = {
    pageSize: 100000,
    pageIndex: 1,
  };
  DeviceCategoryApi.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      tablePointTypeData.value = data.items;
      f_HandleQueryPointLine();
    }
  });
}

// 查询 巡检线路
function f_HandelQueryLine() {
  let params = {
    pageSize: 100,
    pageIndex: 1,
  };
  LineAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      tableLineData.value = data.items.map((item: any) => {
        let tempArr = [];
        if (item.jsonLine.length) {
          JSON.parse(item.jsonLine).coordinates.forEach((ele, eleIndex) => {
            tempArr.push([ele[1], ele[0]]);
          });
        }
        item.checked = true;
        return {
          ...item,
          latlngs: tempArr,
        };
      });
      checkedLineData.value = tableLineData.value;
    }
  });
}

// 查询 隐患名称
function f_HandelQueryDanger() {
  let params = {
    pageIndex: 1,
    pageSize: 10000,
  };
  tableDangerData1.value = [];
  tableDangerData2.value = [];
  DangerAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      let checked = true;
      tableDangerData.value = data.items.map((item: any) => {
        const { coordinates } = JSON.parse(item.jsonPoint);
        item.checked = checked;
        // checked = !checked;
        return {
          ...item,
          latlng: [coordinates[1], coordinates[0]],
        };
      });
      checkedDangerData.value = tableDangerData.value;

      tableDangerData.value.forEach((item) => {
        if (item.status == 0) {
          tableDangerData2.value.push(item);
        } else {
          tableDangerData1.value.push(item);
        }
      });
    }
  });
}

// 显示人员轨迹
function f_ShowDangerList() {
  showLayer.value = false;
  showDangerList.value = !showDangerList.value;
  f_ChangeInspUser(0);
}

// 图层
function f_ShowLayer() {
  showDangerList.value = false;
  showLayer.value = !showLayer.value;
  if (showLayer.value) {
    activeTab.value = "first";
    f_CheckedTableRow("line");
  }
}

// 查询任务对应的隐患
function f_QueryDangerByTaskId(taskId) {
  let params = {
    pageIndex: 1,
    pageSize: 1000,
    TaskId: taskId,
  };
  DangerAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      taskDangerData.value = data.items;
    }
  });
}

// 当天巡检人员轨迹
function f_TodayInspUser() {
  let params = {
    StartTime: "",
    EndTime: "",
  };
  if (inspData.value.status == 1) {
    params.StartTime = moment(new Date()).format("YYYY-MM-DD 00:00:00");
    params.EndTime = moment(new Date()).format("YYYY-MM-DD 23:59:59");
    DangerAPI.api_insp_task_user({}).then(({ data, succeeded }) => {
      if (succeeded) {
        inspUserData.value = data;
        if (inspUserData.value.length) {
          f_HandelQueryDetail(inspUserData.value[0].taskId);
          f_HandelQueryUserPosition(
            inspUserData.value[0].inspUserId,
            params.StartTime,
            params.EndTime
          );
        }
      }
    });
  } else {
    params.StartTime = inspData.value.beginTime;
    params.EndTime = inspData.value.doneTime;
    DangerAPI.api_insp_task_user({}).then(({ data, succeeded }) => {
      if (succeeded) {
        inspUserData.value = data;
        if (inspUserData.value.length) {
          f_HandelQueryDetail(inspUserData.value[0].taskId);
          f_HandelQueryUserPosition(
            inspUserData.value[0].inspUserId,
            params.StartTime,
            params.EndTime
          );
        }
      }
    });
  }
}

// 是否发现隐患
function f_IsDanger(data) {
  let dangerData = find(taskDangerData.value, { pointId: data.point.pointId });
  if (dangerData) {
    return true;
  } else {
    return false;
  }
}

// 查询当前巡检人员对应任务的巡检点
function f_HandelQueryDetail(taskId) {
  TaskSetAPI.api_detail(taskId).then(({ data, succeeded }) => {
    if (succeeded) {
      tableData.value = data;
      f_QueryDangerByTaskId(taskId);
    }
  });
}

// 查询路线对应的区域
function f_HandelQueryAreaByLineId(InspLineId) {
  LineAPI.api_query({ InspLineId: InspLineId, pageIndex: 1, pageSize: 1 }).then(
    ({ data, succeeded }) => {
      if (succeeded) {
        if (data.items && data.items.length) {
          currentInspLineId.value = [];
          if (data.items[0].inspLineType == 2) {
            currentInspLineId.value.push(data.items[0].startPosition.value);
            currentInspLineId.value.push(data.items[0].endPosition.value);
            if (data.items[0].byWay && data.items[0].byWay.length) {
              data.items[0].byWay.forEach((item) => {
                currentInspLineId.value.push(item.value);
              });
            }
          } else {
            currentInspLineId.value = [new Date().getTime()];
          }
        } else {
          currentInspLineId.value = [new Date().getTime()];
        }
        // currentInspLineId.value = ;
      }
    }
  );
}

// 查询当前巡检人员的轨迹
function f_HandelQueryUserPosition(inspUserId, StartTime, EndTime) {
  let params = {
    StartTime: StartTime,
    EndTime: EndTime,
    InspUserIds: inspUserId,
  };
  DangerAPI.api_insp_task_user_position(params).then(({ data, succeeded }) => {
    if (succeeded) {
      currentInspUserPositionData.value = data;
      currentInspUserPositionData.value.forEach((item, index) => {
        currentInspUserPositionData.value[index].positions =
          item.positions.reverse();
      });
    }
  });
}

window.onresize = () => {
  return (() => {
    tableHeight.value = window.innerHeight / 2 - 116;
  })();
};

onBeforeMount(async () => {
  deviceCategoryList.value = await useDeviceCategory();
});

onMounted(() => {
  f_HandelQuery();
  f_HandleQueryPointLineType(); // 先查询管点的大类
  f_HandleQueryPointLine();
  f_HandelQueryLine();
  f_HandelQueryDanger();
  f_HandelQueryPosition();

  // f_TodayInspUser();

  tableHeight.value = window.innerHeight / 2 - 166;
  tableHeightLayer.value = window.innerHeight - 370;
});
</script>
<style scoped lang="scss">
.app-container {
  position: relative;
  overflow: hidden;
  height: calc(100vh - 86px);
}

#map {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  height: 100%;
}

.tool {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 100;
  padding: 8px;
  padding-right: 10px;

  > div {
    display: inline-block;
    padding: 6px 20px;
    background: #fff;
    border-radius: 6px;

    > span {
      margin-left: 20px;
      color: #333;

      :deep .el-switch {
        margin-left: 12px;
      }
    }

    button {
      width: 50px;
      height: 50px;
      font-size: 10px;
      border-radius: 50%;

      :deep span {
        display: inline-block;
      }

      p {
        display: block;
        width: 100%;
        margin: 3px 0;
        font-size: 10px;
      }
    }
  }
}

.content-danger-region {
  position: absolute;
  top: 80px;
  right: 0;
  z-index: 100;
  width: 560px;
  height: calc(100% - 80px);
  background: #ffffffa1;
  .active {
    border: 2px solid rgb(255 203 0) !important;
    box-shadow: 0 0 10px rgb(255 132 7);
  }

  .title {
    height: 40px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    background: linear-gradient(90deg, #299dda, #299dda);
  }

  .search {
    padding: 12px 12px 0;
  }

  .table {
    display: block;
  }

  .content {
    padding: 0 12px 12px;
    height: calc(50% - 10px);
    overflow: auto;
    > .el-row {
      border: 2px solid rgb(221, 203, 102);
      margin-top: 12px;
      padding: 10px;
      border-radius: 6px;
      font-size: 14px;
      background: #fff;
    }
    .danger {
      padding: 10px;
      border-radius: 6px;
      font-size: 14px;
      background: #fff;
      span {
        font-weight: bold;
      }
    }
  }

  :deep .el-form--inline .el-form-item {
    width: 100%;
  }

  :deep .el-tabs {
    padding: 0 10px;
    background: #fff;
  }
}

.content-danger-detail {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 100;
  width: calc(100% - 580px);
  background: #ffffffa1;

  > div {
    width: 100%;
  }

  .title {
    height: 40px;
    padding-left: 20px;
    line-height: 40px;
    color: #fff;
    text-align: left;
    background: linear-gradient(90deg, #299dda, #299dda);
  }

  .search {
    padding: 12px 12px 0;
  }

  .table {
    width: 100%;
    padding: 12px;
  }

  :deep .el-form--inline .el-form-item {
    width: 100%;
  }

  .active {
    border-bottom: 1px solid red;
  }
}
</style>
